import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCselectDemo {
    public static void main(String[] args) throws SQLException {
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/MyJDBC?charaterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");

        Connection connection = dataSource.getConnection();

        String sql = "select * from Student where id = 1";
        PreparedStatement statement = connection.prepareStatement(sql);
        //结果集合,是executeQuery,不是executeUpdate
        ResultSet resultSet = statement.executeQuery();
        //遍历(类似于迭代器遍历),最开始next指针在第一行的最前面,调用一次就往后走一行
        while(resultSet.next()){
            //next 相当于是光标,一直往后指向下一行,移动到结尾 返回false
            //可以用get--来获取每一列
            int ID = resultSet.getInt("id");
            String name = resultSet.getString("name");
            System.out.println(ID+","+name);
        }
        //释放资源,与创建顺序相反
        resultSet.close();
        statement.close();
        connection.close();
    }
}
